package com.ibm.pess.inventory;

import java.util.Date;

import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;
import org.apache.log4j.Logger;

import com.ibm.json.java.JSONArray;
import com.ibm.json.java.JSONObject;
import com.ibm.pess.order.Order;
import com.ibm.pess.rest.RestClient;

public class CargoInEvent implements JavaDelegate {
	private static Logger log = Logger.getLogger("log");

	@Override
	public void execute(DelegateExecution excution) throws Exception {
		// JSONObject resq = new JSONObject();
		// resq.put("msg", "You package arrived Ring @" + (new
		// Date()).toString());
		// RestClient.postJSONObject(
		// "http://nebular.cn.ibm.com:9010/bfo-ext/rest/mqtt/pub", "", "",
		// resq);

		while (!hasTag()) {
			Thread.sleep(2000);
		}

		Order order = (Order) excution.getVariable("order");
		order.setLoc("Inventory 1");
		order.setStatus("in-warehouse");
		order.update();
		excution.setVariable("order", order);
		log.info("cargo in for order " + order.getId());
	}

	private boolean hasTag() {
		boolean rc = false;
		try {
			JSONObject tags = RestClient
					.getJSONObject(
							"http://nebular.cn.ibm.com:9010/bfo-ext/rest/rfid/getTagList",
							"", "");
			JSONArray tagList = (JSONArray) tags.get("tags");
			if (tagList.size() > 0)
				rc = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rc;
	}
}
